package com.icesoft.base.manager.controller.system;

import com.icesoft.base.manager.config.UrlConstant;
import com.icesoft.base.manager.entity.system.SysOrg;
import com.icesoft.base.manager.helper.*;
import com.icesoft.base.manager.service.system.SysOrgService;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.common.helper.TreeBean;
import com.icesoft.core.dao.criteria.Page;
import com.icesoft.core.dao.criteria.QueryBuilder;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 系统部门管理接口
 */
@RequestMapping("system/org")
@RestController
@AllArgsConstructor
public class SysOrgController {
    private final SysOrgService sysOrgService;

    /**
     * 部门查询接口
     */
    @GetMapping(UrlConstant.QUERY)
    public PageResp query(HttpServletRequest request, SysOrg queryParam, String search, PageParam pageParam) {
        QueryBuilder queryBuilder = QueryBuilder.get().asc("pid").desc("id");
        QueryBuilderUtils.addRequestParam(queryBuilder, request, queryParam);
        QueryBuilderUtils.addSearchParam(queryBuilder, search, new String[]{"name"});
        Page<SysOrg> page = sysOrgService.page(queryBuilder, pageParam);
        return new PageResp<>(page);
    }
    /**
     * 部门树查询接口
     */
    @RequestMapping("tree")
    public Resp<List<TreeBean>> tree() {
        AuthUser sysUser = SecurityUtils.getRequiredUser();
        List<SysOrg> orgs = sysOrgService.findByUserId(sysUser.getId(), sysUser.getOrgId());
        Resp<List<TreeBean>> resp = new Resp<>();
        resp.setData(sysOrgService.toTreeBean(orgs));
        return resp;
    }

    /**
     * 部门创建接口
     */
    @PostMapping(value = UrlConstant.CREATE)
    public Resp<?> create(SysOrg model) {
        if (sysOrgService.isExistByPidAndName(model.getPid(), model.getName())) {
            return Resp.error("已存在的组织机构");
        }
        AuthUser authUser = SecurityUtils.getRequiredUser();
        if (!SecurityUtils.isSuperAdmin(authUser)) {
            model.setCompanyId(authUser.getCompanyId());
        }

        sysOrgService.create(model);
        return Resp.success(model.getId());
    }
    /**
     * 部门修改接口
     */
    @PostMapping(value = UrlConstant.UPDATE)
    public Resp update(SysOrg queryParam) {
        sysOrgService.updateNotNullProperties(queryParam);
        return Resp.success(queryParam.getId());
    }
    /**
     * 部门删除接口
     */
    @PostMapping(value = UrlConstant.DELETE)
    public Resp<?> delete(int[] ids) {
        sysOrgService.delete(ids);
        return Resp.success();
    }

}
